package com.yzcrm.erp.crm.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.yzcrm.common.constant.BaseConstant;
import com.yzcrm.erp.admin.service.AdminExamineRecordService;
import com.yzcrm.erp.admin.service.AdminFieldService;
import com.yzcrm.erp.crm.common.CrmEnum;
import com.yzcrm.erp.crm.entity.CrmBusiness;
import com.yzcrm.erp.crm.entity.CrmLeads;
import com.yzcrm.erp.crm.entity.CrmPreSales;
import com.yzcrm.erp.crm.entity.CrmPreSalesBusiness;
import com.yzcrm.utils.AuthUtil;
import com.yzcrm.utils.BaseUtil;
import com.yzcrm.utils.R;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;

public class CrmPreSalesService {

	@Inject
	private CrmRecordService crmRecordService;
	@Inject
	private AdminFieldService adminFieldService;
	@Inject
	private AdminExamineRecordService examineRecordService;
	@Inject
	private CrmBusinessService crmBusinessService;
    /**
     * @author lg
                  * 新增或更新售前信息
     */
    @Before(Tx.class)
    public R addOrUpdate(JSONObject object) {
        CrmPreSales crmPreSales = object.getObject("entity", CrmPreSales.class);
        CrmPreSalesBusiness crmPreSalesBusiness = new CrmPreSalesBusiness();
        String batchId = StrUtil.isNotEmpty(crmPreSales.getBatchId()) ? crmPreSales.getBatchId() : IdUtil.simpleUUID();
        crmRecordService.updateRecord(object.getJSONArray("field"), batchId);
        adminFieldService.save(object.getJSONArray("field"), batchId);
        if (crmPreSales.getPreSalesId() != null) {
        	CrmPreSales preSales = new CrmPreSales().dao().findById(crmPreSales.getPreSalesId());
             if (preSales.getCheckStatus() != 4 && preSales.getCheckStatus() != 2 && preSales.getCheckStatus() != 5) {
                 return R.error("不能编辑，请先撤回再编辑！");
             }

             Map<String, Integer> map = examineRecordService.saveExamineRecord(11, object.getLong("checkUserId"), preSales.getOwnerUserId(),
            		 preSales.getExamineRecordId(), crmPreSales.getCheckStatus());
             if (map.get("status") == 0) {
                 return R.error("没有启动的审核步骤，不能添加！");
             } else {
            	 crmPreSales.setExamineRecordId(map.get("id"));
             }
             if (crmPreSales.getCheckStatus() != null && crmPreSales.getCheckStatus() == 5) {
            	 crmPreSales.setCheckStatus(5);
             } else {
            	 crmPreSales.setCheckStatus(0);
             }
             
             crmPreSales.setUpdateTime(DateUtil.date());
             crmRecordService.updateRecord(new CrmPreSales().dao().findById(crmPreSales.getPreSalesId()), crmPreSales, CrmEnum.CRM_PRE_SALES);
             return crmPreSales.update() ? R.ok() : R.error();
        } else {
        	crmPreSales.setCreateTime(DateUtil.date());
        	crmPreSales.setUpdateTime(DateUtil.date());
        	crmPreSales.setCreateUserId(BaseUtil.getUser().getUserId());
            if (crmPreSales.getOwnerUserId() == null) {
            	crmPreSales.setOwnerUserId(BaseUtil.getUser().getUserId());
            }
            crmPreSales.setBatchId(batchId);
            Map<String, Integer> map = examineRecordService.saveExamineRecord(11, object.getLong("checkUserId"), crmPreSales.getOwnerUserId(), null, crmPreSales.getCheckStatus());
            if (map.get("status") == 0) {
                return R.error("没有启动的审核步骤，不能添加！");
            } else {
            	crmPreSales.setExamineRecordId(map.get("id"));
            }
            if (crmPreSales.getCheckStatus() != null && crmPreSales.getCheckStatus() == 5) {
            	crmPreSales.setCheckStatus(5);
            } else {
            	crmPreSales.setCheckStatus(0);
            }
            boolean save = crmPreSales.save();
            //保存关系数据
            crmPreSalesBusiness.setPreSalesId(crmPreSales.getPreSalesId());
            crmPreSalesBusiness.setCustomerId(crmPreSales.getCustomer_id());
            crmPreSalesBusiness.setBusinessId(crmPreSales.getBusiness_id());
            boolean savePreSalesBusiness = crmPreSalesBusiness.save();
            crmRecordService.addRecord(crmPreSales.getPreSalesId(), CrmEnum.CRM_PRE_SALES);
            return save && savePreSalesBusiness ? R.ok() : R.error();
        }
    }
    
    /**
     * @author lg
     * 根据售前申请id查询
     */
    public Record queryById(Integer preSalesId) {
        Record crmPreSales = Db.findFirst(Db.getSql("crm.preSales.queryById"), preSalesId);
        List<Record> recordList = Db.find("select name,value from `yzcrm_admin_fieldv` where batch_id = ?", crmPreSales.getStr("batch_id"));
        recordList.forEach(field -> crmPreSales.set(field.getStr("name"), field.getStr("value")));
        return crmPreSales;
    }
    
    
    /**
     * @author lg
     * 基本信息
     */
    public List<Record> information(Integer preSalesId) {
        Record record = queryById(preSalesId);
        List<String> keyList = Arrays.asList("pre_sales_expect_time", "pre_sales_latest_time", "remark");
        List<Record> recordList = adminFieldService.queryInformation(CrmEnum.CRM_PRE_SALES, record, keyList);
        recordList.add(new Record().set("name", "客户名称").set("value", new Record().set("customerId", record.getInt("customer_id")).set("customerName", record.getStr("customer_name"))).set("formType", "customer").set("field_type", 1));
        recordList.add(new Record().set("name", "商机名称").set("value", new Record().set("businessId", record.getInt("business_id")).set("businessName", record.getStr("business_name"))).set("formType", "business").set("field_type", 1));
        return recordList.stream().sorted(Comparator.comparingInt(r -> -r.getInt("field_type"))).map(r -> r.remove("field_type", "field_name", "setting", "type")).collect(Collectors.toList());
    }
    
    /**
     * @author lg
     * 查询编辑字段
     */
    public List<Record> queryField(Integer preSalesId) {
        Record record = queryById(preSalesId);
        List<Record> businessList = new ArrayList<>();
        Record business = new Record();
        // businessList.add(business.set("business_id", record.getInt("business_id")).set("business_name", record.getStr("business_name")));
        // record.set("business_id", businessList);

        List<Record> fieldList = adminFieldService.queryUpdateField(CrmEnum.CRM_PRE_SALES.getType(), record);
        return fieldList;
    }

    /**
     * @author lg
     * 根据售前id变更负责人
     */
    @Before(Tx.class)
    public R updateOwnerUser(CrmPreSales crmPreSales) {
        String[] preSalesIdsArr = crmPreSales.getPreSalesIds().split(",");
        for (String preSalesId : preSalesIdsArr) {
            if (!BaseUtil.getUserId().equals(BaseConstant.SUPER_ADMIN_USER_ID) && !AuthUtil.isRwAuth(Integer.parseInt(preSalesId), "preSales")) {
                return R.error("无权限变更责任人");
            }
            crmPreSales.setPreSalesId(Integer.valueOf(preSalesId));
            crmPreSales.setOwnerUserId(crmPreSales.getNewOwnerUserId());
            crmPreSales.update();
            crmRecordService.addConversionRecord(Integer.valueOf(preSalesId), CrmEnum.CRM_PRE_SALES, crmPreSales.getNewOwnerUserId());
        }
        return R.ok();
    }
    
    /**
     * @author lg
     * 接受售前申请
     */
    @Before(Tx.class)
    public R acceptPreSales(CrmPreSales crmPreSales) {
        String[] preSalesIdsArr = crmPreSales.getPreSalesIds().split(",");
        Long nowUserId = BaseUtil.getUser().getUserId();
        for (String preSalesId : preSalesIdsArr) {
            crmPreSales.setPreSalesId(Integer.valueOf(preSalesId));
            crmPreSales.setIsAccept(1);
            Record record = Db.findFirst(Db.getSql("crm.preSales.queryById"), preSalesId);
            if(nowUserId != record.getLong("owner_user_id")) {
            	return R.error("非责任人，不能接受该售前申请");
            }
            crmRecordService.addAcceptPreSalesRecord(Integer.valueOf(preSalesId), CrmEnum.CRM_PRE_SALES, record.getLong("owner_user_id"));
            //将人员添加到商机的相关团队中
            CrmBusiness crmBusiness = new CrmBusiness();
            crmBusiness.setIds("" + record.getInt("business_id"));
            crmBusiness.setMemberIds("" + record.getLong("owner_user_id"));
            crmBusiness.setPower(2);
            R r = crmBusinessService.addMember(crmBusiness,2);
            if((int)r.get("code") == 200) {
            	crmPreSales.update();
            }else {
            	return r;
            }
            
        }
        return R.ok();
    }
    

    /**
     * @author lg
     * 根据id删除售前
     */
    public R deleteByIds(String preSalesIds){
        String[] idsArr = preSalesIds.split(",");
        List<Record> idsList = new ArrayList<>();
        for(String id : idsArr){
            if(!BaseUtil.getUserId().equals(BaseConstant.SUPER_ADMIN_USER_ID) && !BaseUtil.getUser().getRoles().contains(BaseConstant.SUPER_ADMIN_ROLE_ID) && Db.queryInt(Db.getSql("crm.customer.queryIsRoUser"), BaseUtil.getUserId(), id) > 0){
                return R.error("没有权限");
            }
            Record record = new Record();
            idsList.add(record.set("pre_sales_id", Integer.valueOf(id)));
        }
        
        return Db.tx(() -> {
            Db.batch(Db.getSql("crm.preSales.deleteByIds"), "pre_sales_id", idsList, 100);
            //删除售前申请与商机的关联
            Db.batch(Db.getSql("crm.preSales.deleteBusinessAndPreSalesByIds"), "pre_sales_id", idsList, 100);
            return true;
        }) ? R.ok() : R.error();
    }
    
}
